<template>
  <el-upload
    v-model:file-list="fileList"
    action="#"
    list-type="picture-card"
    :before-upload="beforeUpload"
    :http-request="customUpload"
    :on-preview="handlePictureCardPreview"
    :class="uploadClass"
    :on-remove="
      (file, fileList) => {
        handleRemove(file, fileList, props.form);
      }
    "
    ref="uploadRef"
  >
    <div class="text-center">
      <div>
        <CardSvg :svg-type="props.form.svgType ? props.form.svgType : 1"></CardSvg>
      </div>
    </div>
    <template #tip v-if="props.form.tip ? props.form.tip : false">
      <div class="text-[#6B678E] text-14px">
        {{ props.form.tip }}
      </div>
    </template>
  </el-upload>

  <el-dialog v-model="dialogVisible">
    <div class="text-center">
      <el-image w-full :src="dialogImageUrl" alt="Preview Image" />
    </div>
  </el-dialog>
</template>

<script lang="ts" setup>
  import { computed, ref, watch } from "vue";
  import CardSvg from "../CardSvg/index.vue";
  import { ElMessage } from "element-plus";

  const uploadRef = ref(null);
  const disabled = ref(false);
  const props = defineProps({
    form: {
      type: Object,
      default: () => ({}),
    },
  });
  const emits = defineEmits(["customUpload", "handleRemove"]);

  const fileList = ref(...props.form.fileList);

  const dialogImageUrl = ref("");
  const dialogVisible = ref(false);
  const isShow = ref(true);

  const handleRemove = (file, fileList, form) => {
    // console.log(uploadFile, uploadFiles);
    console.log(file, fileList, form);
    emits("handleRemove", { file, fileList, form });
  };

  const handlePictureCardPreview = uploadFile => {
    dialogImageUrl.value = uploadFile.url!;
    dialogVisible.value = true;
  };
  const beforeUpload = file => {
    if (props.form.prop == "customerLogo") {
      const typeList = ["jpg", "jpeg", "png", "gif"];
      let fileType = file.name.split(".").slice(-1)[0].toLowerCase();
      const isLt10M = file.size / 1024 / 1024 < 10; // 10MB限制
      const imgWidth = 700; // 示例宽度限制
      const imgHeight = 700; // 示例高度限制
      return new Promise((resolve, reject) => {
        if (typeList.indexOf(fileType) === -1) {
          ElMessage.error("图片格式只能为jpg/jpeg/png/gif");
          return reject(false);
        }
        if (!isLt10M) {
          ElMessage.error("上传图片大小不能超过 10MB!");
          return reject(false);
        }
        // 使用FileReader来读取图片文件并获取其尺寸信息
        const reader = new FileReader();
        reader.onload = e => {
          const img = new Image();
          img.onload = () => {
            // console.log(img.width, img.height);
            // resolve(true)
            if (img.width >= imgWidth && img.height >= imgHeight) {
              resolve(true);
            } else {
              ElMessage.error(`图片尺寸需要大于${imgWidth}*${imgHeight}，请重新上传`);
              reject(false);
            }
          };
          if (typeof e.target.result === "string") {
            img.src = e.target.result;
          } // 设置图片源为读取的结果，触发onload事件
        };
        reader.readAsDataURL(file); // 以DataURL的形式读取文件内容
      });
    } else {
      const typeList = ["jpg", "jpeg", "png", "gif"];
      let fileType = file.name.split(".").slice(-1)[0].toLowerCase();
      const isLt10M = file.size / 1024 / 1024 < 10; // 10MB限制
      return new Promise((resolve, reject) => {
        if (typeList.indexOf(fileType) === -1) {
          ElMessage.error("图片格式只能为jpg/jpeg/png/gif");
          return reject(false);
        }
        if (!isLt10M) {
          ElMessage.error("上传图片大小不能超过 10MB!");
          return reject(false);
        }
        resolve(true);
      });
    }
  };

  const customUpload = options => {
    // console.log(options,"options")

    const { file, onSuccess, onError } = options;
    console.log(file);
    emits("customUpload", { file, form: props.form });
    // console.log(file,'file')
  };
  const uploadClass = computed(() => {
    if (props.form.prop !== "contractList") {
      if (fileList.value && fileList.value.length) {
        return "upload-demo";
      } else {
        return "";
      }
    } else {
      return "";
    }
  });
  defineExpose({
    fileList: fileList.value,
  });
  watch(
    () => props.form,
    newValue => {
      if (newValue) {
        fileList.value = newValue.fileList;
      }
    },
    {
      deep: true,
      immediate: true,
    }
  );
</script>
<style lang="scss" scoped>
  .upload-demo {
    :deep(.el-upload-list .el-upload--picture-card) {
      display: none;
    }
  }
</style>
